#Alexander F. Gazmararian
#afg2@princeton.edu
#January 19, 2024

#load packages
library(tidyverse)
library(sandwich)
library(lmtest)
library(modelsummary)
library(kableExtra)
library(broom)
library(scales)
library(viridis)
library(here)

#Load custom functions
source(here("code", "fun", "savefig.r"))
source(here("code", "fun", "gofmap.r"))
source(here("code", "fun", "fix_txt.r"))

#Load data
g <- readRDS(here("data", "qualtrics", "natsurvey.rds"))

#Specify baseline model
f.base <- y ~ age + female + black + hispanic + aapi + rural_bin + college + fullemploy + pid3 + ownhome + income5 + buyself_bin + suitable_bin + index_trust + altruism + risk

#Coefficient mapping for tables
coefmap <- c(
  "flytreat"="Flywheel Prime",
  "flytreat:risk"="Flywheel Prime x Risk Preferences",
  "flytreat:altruism"="Flywheel Prime x Altruism",
  "flytreat:index_trust" = "Flywheel Prime x Trust Index",
  "flytreat:buyself_bin"="Flywheel Prime x Solar Interest",
  "flytreat:pid3Republican"="Flywheel Prime x Republican",
  "flytreat:pid3Neither"="Flywheel Prime x Neither"
)

# Specify model
m <- list()
m[[1]] <- lm(update(f.base, fly_num ~ flytreat + .), g)
m[[2]] <- lm(update(f.base, fly_num ~ flytreat * risk + .), g)
m[[3]] <- lm(update(f.base, fly_num ~ flytreat * altruism + .), g)
m[[4]] <- lm(update(f.base, fly_num ~ flytreat * index_trust + .), g)
m[[5]] <- lm(update(f.base, fly_num ~ flytreat * buyself_bin + .), g)
# Create table
file <- here("output", "tables", "tab_flywheel.txt")
modelsummary(
  m,
  stars = c("*"=.1,"**"=.05,"***"=.01),
  vcov = "HC2",
  coef_map = coefmap,
  gof_map = gof_map,
  gof_omit = "R2|IC|Log|F|RMSE|Err",
  escape = FALSE,
  output = "latex",
  add_rows = data.frame(
    c("Covariates"),
    c("Yes"),
    c("Yes"),
    c("Yes"),
    c("Yes"),
    c("Yes")
  )
) %>%
  kable_styling(latex_options=c("scale_down","HOLD_position")) %>%
  cat(., file = file)
fix_txt(file)
